home *** CD-ROM | disk | FTP | other *** search
- Path: EU.net!sun4nl!ittpub!ittpub!nntp
- Newsgroups: comp.lang.c++
- Subject: Re: maybe a FAQ... how to ensure the order in which global constructors
- Message-ID: <1996Jan18.152308.1748@ittpub>
- From: wil@ittpub.nl (Wil Evers)
- Date: 18 Jan 96 15:23:08 WET
- References: <4d3gni$pmp@inet01.colgate.edu>
- Distribution: world
- Nntp-Posting-Host: lintilla
-
- In article <4d3gni$pmp@inet01.colgate.edu> jwilson@center.colgate.edu
- (KRSNA CONSCIOUSNESS NOW) writes:
-
- > [snip]
- > I subclassed Handle to RegisterHandle, and as part of the constructor of
- > RegisterHandle, the new RegisterHandle is automatically added to a
- > global Registry. Or I would so; this only works if the global registry
- > has been constructed prior to the construction of the RegisterHandle.
- > [snip]
- > Is there a mechanism for ensuring that global constructors are called in
- > a certain order?
-
- Global objects are constructed in order of definition in their translation
- units (source file). There is no guarantee of any ordering when two global
- objects are defined in different translation units.
-
- You can force a particular object to be initialized (yes, initialized,
- which is not the same as constructed) by using what is called the
- nifty_counter idiom. If you put this in some header file (say, "nifty.h"):
-
- class nifty_counter {
- static int cnt = 0;
- public :
- nifty_counter();
- ~nifty_counter();
- };
-
- static nifty_counter nifty;
-
- and this in some implementation file:
-
- int nifty_counter::cnt = 0;
-
- nifty_counter::nifty_counter()
- {
- if (cnt++ == 0) {
- // initialize here
- }
- }
-
- nifty_counter::~nifty_counter()
- {
- if (--cnt == 0) {
- // uninitialize here
- }
- }
-
- then every object defined below an #include "nifty.h" can count on the
- fact that the initialization took place before its constructor is run.
-
- Unfortunately, this is only half the story, since the initialization you
- would like to do might interfere with the constructor of the object you're
- trying to initialize. Some special tricks, like giving the global object a
- 'do nothing' constructor and a separate init() member function or
- constructing the object via 'placement new' in a raw memory area, are
- needed to make this work properly.
-
- Hope this helps,
-
- - Wil
-